#!/bin/bash
# vim: fdm=marker fmr=[[[,]]] cms=\ #%s

[[ -z $SOAR ]] && SOAR=/opt/soar
PATH=$PATH:$SOAR/common/bash/soar
. soar.sh

usage()
{ #[[[
    echo "Usage: $(basename $0) SERVER"
} #]]]

main()
{ #[[[
    if [[ -z $SVCENV_CNFG ]]
    then
        echo "Error: SVCENV_CNFG not set"
        return 1
    fi
    local svr=svr_$1
    if [[ $svr == "svr_" ]]
    then
        usage
        return 1
    fi

    local svr_cnfg=$(cnfg_get_property "$SVCENV_CNFG" SERVER $svr)
    if [[ -z $svr_cnfg ]]
    then
        echo "Error: no $svr in \$SVCENV_CNFG"
        return 1
    fi
    local ipckey=$(cnfg_get_property "$SVCENV_CNFG" GLOBAL IPCKEY)
    if [[ -z $ipckey ]]
    then
        echo "Error: IPCKEY in \$SVCENV_CNFG invalid"
        return 1
    fi

    local running

    running=$(process_is_running $svr)
    if (( ! running ))
    then
        echo "$svr has already stopped... skip"
        return 0
    fi

    local svr_addr="/tmp/${svr}_monitor_${ipckey}"
    local respond=$(echo "SHUTDOWN" | nc -U $svr_addr)
    if [[ -z $respond ]]
    then
        echo "Error: down $svr no response"
        return 1
    fi
    echo ${respond%.*}
    sleep 1

    running=$(process_is_running $svr)
    if (( ! running ))
    then
        echo "$svr stop succeed"
        return 0
    else
        echo "$svr stop fail"
        return 1
    fi
} #]]]

main $@
exit $?
